package grimbo.goodwinfooty.server.mvc;

import grimbo.goodwinfooty.server.ByteUtils;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.fileupload.FileItemStream;

/**
 * Handles a single file parameter.
 */
public class SingleFileItemStreamHandler implements FileItemStreamHandler {
	private String fileParam;
	private byte[] fileBytes;

	public SingleFileItemStreamHandler(String fileParam) {
		if ((null == fileParam) || ("".equals(fileParam.trim()))) {
			throw new IllegalArgumentException(
					"fileParam cannot be null or blank");
		}
		this.fileParam = fileParam;
	}

	@Override
	public void handleFileItemStream(FileItemStream item) throws IOException {
		String name = item.getFieldName();
		if (!name.equals(fileParam)) {
			return;
		}

		if (!item.isFormField()) {
			InputStream in = item.openStream();
			fileBytes = ByteUtils.readStream(in);
		}
	}

	public String getFileParam() {
		return fileParam;
	}

	public byte[] getFileBytes() {
		return fileBytes;
	}
}
